package com.nerins.udp.server;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class RBACResponseEncoder extends ProtocolEncoderAdapter {

    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {

        int bufLen = 0;
        
        RBACResponse response = (RBACResponse) message;

        //type
        bufLen += Integer.SIZE /8;
        
        //version
        bufLen += Integer.SIZE /8;
        
        //id
        final byte[] requestId = response.getRequestId().getBytes("ISO-8859-1");

        //id len
        bufLen += requestId.length;

        //responseContent
        final byte[] responseContent = response.getResponseContent().getBytes("ISO-8859-1");

        //responseContent len
        bufLen += responseContent.length;
        
        //buffer to write
        IoBuffer buffer = IoBuffer.allocate(bufLen, false);
        
        buffer.putInt(response.getResponseType());
        buffer.putInt(response.getResponseVersion());
        buffer.putInt(requestId.length);
        buffer.put(requestId);
        buffer.putInt(responseContent.length);
        buffer.put(responseContent);
        buffer.flip();
        out.write(buffer);
    }

}